package com.neusoft.lohas.common.restTemplate.client;

import java.io.IOException;
import java.io.InputStream;

import org.springframework.core.io.AbstractResource;
import org.springframework.core.io.InputStreamResource;

public class CellInputStreamResource extends AbstractResource {

	private final InputStream inputStream;

	private final String description;

	private boolean read = false;
	
	private int contentLength;


	/**
	 * Create a new InputStreamResource.
	 * @param inputStream the InputStream to use
	 * @throws IOException 
	 */
	public CellInputStreamResource(InputStream inputStream) throws IOException {
		this(inputStream, "resource loaded through InputStream");
	}

	/**
	 * Create a new InputStreamResource.
	 * @param inputStream the InputStream to use
	 * @param description where the InputStream comes from
	 * @throws IOException 
	 */
	public CellInputStreamResource(InputStream inputStream, String description) throws IOException {
		if (inputStream == null) {
			throw new IllegalArgumentException("InputStream must not be null");
		}
		this.inputStream = inputStream;
		this.description = (description != null ? description : "");
	
			this.contentLength = inputStream.available();
		
	}


	/**
	 * This implementation always returns {@code true}.
	 */
	@Override
	public boolean exists() {
		return true;
	}

	/**
	 * This implementation always returns {@code true}.
	 */
	@Override
	public boolean isOpen() {
		return true;
	}

	/**
	 * This implementation throws IllegalStateException if attempting to
	 * read the underlying stream multiple times.
	 */
	public InputStream getInputStream() throws IOException, IllegalStateException {
		if (this.read) {
			throw new IllegalStateException("InputStream has already been read - " +
					"do not use InputStreamResource if a stream needs to be read multiple times");
		}
		this.read = true;
		return this.inputStream;
	}

	/**
	 * This implementation returns the passed-in description, if any.
	 */
	public String getDescription() {
		return this.description;
	}

	

	@Override
	public long contentLength() throws IOException {
		return this.contentLength;
	}

	/**
	 * This implementation compares the underlying InputStream.
	 */
	@Override
	public boolean equals(Object obj) {
		try {
			return (obj == this ||
				(obj instanceof InputStreamResource && ((InputStreamResource) obj).getInputStream().equals(this.inputStream)));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * This implementation returns the hash code of the underlying InputStream.
	 */
	@Override
	public int hashCode() {
		return this.inputStream.hashCode();
	}
}
